package com.nycreativity.elecreativity.service.impl

import com.google.common.cache.CacheBuilder
import com.google.common.cache.CacheLoader
import com.google.common.cache.LoadingCache
import com.nycreativity.elecreativity.entity.enums.SmsSignEnum
import com.nycreativity.elecreativity.entity.enums.SmsTemplateEnum
import com.nycreativity.elecreativity.service.SmsService
import com.nycreativity.elecreativity.util.sms.SmsCache
import com.nycreativity.elecreativity.util.sms.SmsUtil
import org.springframework.stereotype.Service
import java.util.*
import java.util.concurrent.TimeUnit
import javax.annotation.Resource

@Service
class SmsServiceImpl : SmsService {

    companion object {
        /**
         * 验证码过期时间（分钟），与SmsCache要保持一致
         */
        const val EXPIRATION: String = "5"
    }

    @Resource
    lateinit var smsUtil: SmsUtil

    override fun getValidCode(phoneNum: String) {
        val code = (Random().nextInt(9999) + 1000).toString();
        if (smsUtil.isDomestic(phoneNum)) {
            smsUtil.sendValidateCodeSms(SmsSignEnum.DOMESTIC, SmsTemplateEnum.DOMESTIC_VALID_CODE, code, EXPIRATION, phoneNum)
        }else{
            smsUtil.sendValidateCodeSms(SmsSignEnum.INTERNATIONAL, SmsTemplateEnum.INTERNATIONAL_VALID_CODE, code, EXPIRATION, phoneNum)
        }
        //设置缓存
        SmsCache.put(phoneNum, code);
    }

    override fun validateCode(phoneNum: String, code: String): Boolean {
        val savedCode = SmsCache.get(phoneNum)
        if (savedCode != null && savedCode == code){
            return true
        }
        return false
    }

}